package com.wizz.trade.information.controller;

import com.wizz.trade.common.PageVo;
import com.wizz.trade.information.dto.ItemDto;
import com.wizz.trade.information.dto.page.ItemPageDto;
import com.wizz.trade.information.entity.Item;
import com.wizz.trade.information.service.ItemService;
import com.wizz.trade.common.ResponseResult;
import com.wizz.trade.common.constant.StatusCode;
import com.wizz.trade.information.vo.ItemVo;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 资料模块/收费项目
 */
@RestController
@RequestMapping("/item")
public class ItemController {

    @Resource
    private ItemService itemService;

    /**
     * 添加操作
     * @param itemDto
     * @return
     */
    @PostMapping
    @PreAuthorize("hasAuthority('设置商品资料')")

    public ResponseResult addItem(@RequestBody ItemDto itemDto) {
        Item item = new Item();
        BeanUtils.copyProperties(itemDto,item);
        itemService.addItem(item);
        return new ResponseResult<>(StatusCode.OK, "添加成功" );
    }

    /**
     * 更新（编辑）操作
     * @param itemDto
     * @param id
     * @return
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('设置商品资料')")

    public ResponseResult updateItem(@RequestBody ItemDto itemDto, @PathVariable("id") Integer id) {
        Item item = new Item();
        BeanUtils.copyProperties(itemDto,item);
        item.setId(id);
        itemService.updateItem(item);
        return new ResponseResult<>(StatusCode.OK, "修改成功");
    }

    /**
     * 删除（撤销）操作
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('设置商品资料')")

    public ResponseResult deleteItem(@PathVariable("id") Integer id) {
        itemService.deleteItem(id);
        return new ResponseResult<>(StatusCode.OK, "删除成功");
    }

    /**
     * 分页刷新、条件查询
     * @param itemPageDto
     * @return
     */
    @GetMapping("/page")
    @PreAuthorize("hasAuthority('设置商品资料')")

    public ResponseResult<PageVo<ItemVo>> list(ItemPageDto itemPageDto){
        PageVo<Item> rawPage = itemService.getPage(itemPageDto);
        List<Item> data = rawPage.getData();
        List<ItemVo> dataVo = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            ItemVo  itemVo = new ItemVo();
            BeanUtils.copyProperties(data.get(i), itemVo);
            dataVo.add(itemVo);
        }
        return new ResponseResult<>(StatusCode.OK, new PageVo<>(rawPage.getPages(), rawPage.getTotal(), dataVo));
    }
}
